/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.core;

import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import com.google.code.motoo.utils.ExpiringMap;

/**
 * 
 * @author linfengqi
 * @version 1.0  Jun 2, 2009
 */
public class IoSessionRecycler {

	private static ExpiringMap<Object, IoSession> sessionMap = new ExpiringMap<Object, IoSession>();

	private static ExpiringMap<Object, IoSession>.Expirer mapExpirer = sessionMap.getExpirer();
	
	public void register(IoSession session) {
		mapExpirer.startExpiringIfNotStarted();

		Object key = generateKey(session);
		if (!sessionMap.containsKey(key)) {
            sessionMap.put(key, session);
        }
	}

	public IoSession lookup(SocketAddress localAddress, SocketAddress remoteAddress) {
		return sessionMap.get(generateKey(localAddress, remoteAddress));
	}

	public void remove(IoSession session) {
		sessionMap.remove(generateKey(session));
	}
	
	public ExpiringMap<Object, IoSession> containor() {
		return sessionMap;
	}
	
	public void stopExpiring() {
        mapExpirer.stopExpiring();
    }

    public int getExpirationInterval() {
        return sessionMap.getExpirationInterval();
    }

    public int getTimeToLive() {
        return sessionMap.getTimeToLive();
    }

    public void setExpirationInterval(int expirationInterval) {
        sessionMap.setExpirationInterval(expirationInterval);
    }

    public void setTimeToLive(int timeToLive) {
        sessionMap.setTimeToLive(timeToLive);
    }

	private Object generateKey(IoSession session) {
		return generateKey(session.getLocalAddress(), session.getRemoteAddress());
	}

	private Object generateKey(SocketAddress localAddress, SocketAddress remoteAddress) {
		List<SocketAddress> key = new ArrayList<SocketAddress>(2);
		key.add(remoteAddress);
		key.add(localAddress);
		return key;
	}

}
